package com.keeping.aiimagery.controller;

import cn.hutool.core.convert.ConvertException;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.api.internal.util.file.FileUtils;
import com.keeping.aiimagery.service.UserService;
import com.keeping.aiimagery.service.impl.OrdersServicesServiceImpl;
import org.bouncycastle.util.encoders.UTF8;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Controller
public class AIGPTController {

    /**
     * 设置聊天api接口
     */
    static String chatEndpoint = "https://api.openai.com/v1/chat/completions";
    /**
     * 设置api密钥
     */
    static String apiKey = "Bearer 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";

    @Resource
    private OrdersServicesServiceImpl ordersServicesServiceImpl;




    private static String StoreSavePath = "messageList/";
    static {
        File file = new File(StoreSavePath);
//        System.out.println(StoreSavePath);
//        System.out.println(file.getPath());
        if(!file.exists()){
            System.out.println("没有这个目录，正在创建");
            file.mkdir();
        }else{
            System.out.println("存在这个目录");
        }
    }
    @GetMapping("/getMessageList")
    public void getMessageList(String user,HttpServletResponse response) throws Exception{
//        user = "test1";//测试案例
//        response.setCharacterEncoding("UTF-8");
        File file = new File(StoreSavePath + user + ".json");
        if(!file.exists()){
            FileOutputStream fileOutputStream = new FileOutputStream(StoreSavePath + user + ".json");
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8);
            JSONObject entries = new JSONObject();
            HashMap<String, String> stringStringHashMap = new HashMap<>();
            stringStringHashMap.put("tags",new ArrayList<>().toString());
            entries.putAll(stringStringHashMap);
            outputStreamWriter.write(entries.toString());
            outputStreamWriter.close();
//            return;
        }
        try {
            String raw = FileUtils.readFileToString(new File(StoreSavePath+user+".json"),StandardCharsets.UTF_8);
            JSONObject entries = new JSONObject(raw);
            PrintWriter writer = response.getWriter();
            writer.write(entries.toString());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @PutMapping("/addChat")
    @ResponseBody
    public String addChat(@RequestBody String newChat) throws IOException {
        String user = new JSONObject(newChat).get("user").toString();
        String raw = FileUtils.readFileToString(new File(StoreSavePath + user + ".json"),StandardCharsets.UTF_8);
        JSONObject entries = new JSONObject(raw);
        JSONObject entries1 = new JSONObject(newChat).getJSONObject("data");
        JSONArray tags = new JSONArray(entries.get("tags"));
        tags.add(entries1.get("name").toString());
        entries.put("tags",tags);
        entries.put(entries1.get("name").toString(),new JSONArray());
        FileOutputStream file = new FileOutputStream(StoreSavePath + user + ".json");
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(file, StandardCharsets.UTF_8);
        outputStreamWriter.write(entries.toString());
        outputStreamWriter.close();
        return "success";
    }

    @PutMapping("/editChatName")
    @ResponseBody
    public String editChat(@RequestBody String data) throws IOException {
        JSONObject entries = new JSONObject(data);
        String oldName = entries.get("oldName").toString();
        String newName = entries.get("newName").toString();
        String user = entries.get("user").toString();
        String raw = FileUtils.readFileToString(new File(StoreSavePath + user + ".json"),StandardCharsets.UTF_8);

        JSONObject entries1 = JSONUtil.parseObj(raw);
        entries1.put(newName,entries1.get(oldName));
        entries1.remove(oldName);

        JSONArray tags = entries1.getJSONArray("tags");
        tags.remove(oldName);
        tags.put(newName);
        entries1.remove("tags");
        entries1.put("tags",tags);
//        System.out.println(entries1);
        FileOutputStream file = new FileOutputStream(StoreSavePath + user + ".json");
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(file, StandardCharsets.UTF_8);
        outputStreamWriter.write(entries1.toString());
        outputStreamWriter.close();
        return "Done";
    }

    @DeleteMapping("/deleteChat")
    @ResponseBody
    public String deleteChat(@RequestBody String data) throws IOException {
        JSONObject entries = new JSONObject(data);
        String user = entries.get("user").toString();
        String target = entries.get("target").toString();

        String raw = FileUtils.readFileToString(new File(StoreSavePath + user + ".json"),StandardCharsets.UTF_8);

        JSONObject entries1 = JSONUtil.parseObj(raw);
        entries1.remove(target);
        JSONArray tags = new JSONArray(entries1.get("tags"));
        tags.remove(target);
        entries1.put("tags",tags);


        FileOutputStream file = new FileOutputStream(StoreSavePath + user + ".json");
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(file, StandardCharsets.UTF_8);
        outputStreamWriter.write(entries1.toString());
        outputStreamWriter.close();
        return "Done";
    }



    @PostMapping("/chat")
    @ResponseBody
    public String letChat(@RequestBody String data,HttpServletResponse response)throws Exception{
        System.out.println(data);
        JSONObject json = new JSONObject(data).getJSONObject("data");
        String user = new JSONObject(data).get("user").toString();
        File file = new File(StoreSavePath + user + ".json");
        try {
            String raw = FileUtils.readFileToString(file,StandardCharsets.UTF_8);
            JSONObject entries = new JSONObject(raw);
            JSONArray objects = new JSONArray(entries.get(json.get("name")).toString());
            JSONObject js = new JSONObject();
            js.put("role","user");
            js.put("content",json.get("content"));
            objects.add(js);
            String chat = chat(objects);
            js = new JSONObject();
            js.put("role","assistant");
            js.put("content",chat);
            objects.add(js);
            entries.put(json.get("name").toString(),objects);
//            System.out.println(entries);
            FileOutputStream fileOutputStream = new FileOutputStream(StoreSavePath + user + ".json");
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8);
            outputStreamWriter.write(entries.toString());
            outputStreamWriter.close();
            System.out.println(user);
            ordersServicesServiceImpl.cut(user,1,"chatGPT");
//            new FileWriter(file.getPath()).write(entries.toString());
            return chat;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public String chat(JSONArray dataList ){
        Map<String , Object> paramMap = new HashMap<>();
        paramMap.put("model","gpt-3.5-turbo");
        paramMap.put("temperature",0.8);
        paramMap.put("messages",dataList);
        JSONObject message = null;
        /**
         * 设置代理
         */
        String proxyHost = "127.0.0.1";
        int proxyPort = 7890;
        Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(proxyHost,proxyPort));
        try{
            String body = HttpRequest.post(chatEndpoint)
                    .setProxy(proxy)
                    .header("Authorization",apiKey)
                    .header("Content-Type","application/json")
                    .body(JSONUtil.toJsonStr(paramMap))
                    .execute()
                    .body();
//            System.out.println(body);
            JSONObject jsonObject = JSONUtil.parseObj(body);
            JSONArray choices = jsonObject.getJSONArray("choices");
            if(choices==null) return "That model is currently overloaded with other requests. You can retry your request";
            JSONObject result = choices.get(0,JSONObject.class,Boolean.TRUE);
            message = result.getJSONObject("message");
        }catch (HttpException e){
            e.printStackTrace();
        }catch (ConvertException e){
            e.printStackTrace();
        }
        return message.getStr("content");
    }
}
